package com.pomelo.base.core.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.pomelo.base.core.bean.PageParam;

import cn.hutool.core.codec.Base64;

/**
 * 前端工具
 *
 * @author biankudingcha
 * @date: 2021-09-26
 * @since 0.5.0
 */
public class HttpUtil {

    /**
     * http://localhost:8080
     */
    public static String getDomainPath() {
        int port = getRequest().getServerPort();
        String domainPath = getRequest().getScheme() + "://" + getRequest().getServerName();
        if (port != 80) {
            domainPath = domainPath + ":" + port;
        }
        return domainPath;
    }

    /**
     * /上下文根
     */
    public static String getContextPath() {
        return getRequest().getContextPath();
    }

    /**
     * http://localhost:8080/basePath
     */
    public static String getBasePath() {
        return getDomainPath() + getContextPath();
    }

    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        return request;
    }

    public static HttpServletResponse getResponse() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        HttpServletResponse request = ((ServletRequestAttributes) requestAttributes).getResponse();
        return request;
    }

    public static String getIpAddr() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (ip.equals("127.0.0.1")) {
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ip = inet.getHostAddress();
            }
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }

    public static String getParameter(String name) {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        return request.getParameter(name);
    }

    public static String getParameterDecodeBase64(String name) {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        String value = request.getParameter(name);
        if (value == null || "".equals(value)) {
            return value;
        }
        String decodeValue = Base64.decodeStr(value);
        return decodeValue;
    }

    public static Map<String, Object> getParameterMap() {
        Map<String, Object> param = new HashMap<String, Object>();
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            param.put(name, request.getParameter(name));
        }
        return param;
    }

    public static Map<String, Object> getParameterMap(HttpServletRequest request) {
        Map<String, Object> param = new HashMap<String, Object>();
        if (request == null) {
            return null;
        }
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            param.put(name, request.getParameter(name));
        }
        return param;
    }

    public static String getWebInfRealPath() {
        return getRequest().getSession().getServletContext().getRealPath("/WEB-INF");
    }

    public static PageParam getPageParam() {
        HttpServletRequest request = getRequest();
        int pageIndex = StringUtil.toInt(request.getParameter("pageIndex"), 0);
        int pageSize = StringUtil.toInt(request.getParameter("pageSize"), 0);
        String sort = StringUtil.toStr(request.getParameter("sort"));
        PageParam pageParam = new PageParam();
        pageParam.setPageIndex(pageIndex);
        pageParam.setPageSize(pageSize);
        pageParam.setSort(sort);
        return pageParam;
    }
}
